package com.yyk.dzvisit.service.his;

import com.alibaba.fastjson.JSONObject;
import com.yyk.dzvisit.common.CustomConstant;
import com.yyk.dzvisit.enums.BizErrorEnum;
import com.yyk.dzvisit.exception.BusinessException;
import com.yyk.dzvisit.util.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

/**
 * @Desecription: HIS业务接口
 * @Autor: wxl
 * @Date: 2020/7/16 13:23
 */
@Slf4j
@Service
public class HISBusinessService {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${his.hisUrl}")
    private String hisUrl;


    public JSONObject invoke(String input) {
        MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<>();
        requestEntity.add("Input", input);//"<Request><TradeCode>1000</TradeCode></Request>"
        requestEntity.add("soap_method", "DHCSelfPay");
        requestEntity.add("CacheUserName", "dhsyslogin");
        requestEntity.add("CachePassword", "1q2w3e4r%T6y7u8i9o0p");
        requestEntity.add("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");

        //HIS调用
        String response;
        try {
            response = restTemplate.postForObject(hisUrl, requestEntity, String.class);

        } catch (RestClientException e) {
            log.error(e.getMessage());
            throw new BusinessException(BizErrorEnum.HIS_REMOTE_EXCEPTION);
        }
        //HIS数据转换
        JSONObject responseJson = CommonUtil.xmlToJson(response);
        String dHCSelfPayResultXml = responseJson.getJSONObject("Body").getJSONObject("DHCSelfPayResponse").getString("DHCSelfPayResult");
        JSONObject dHCSelfPayResult = CommonUtil.xmlToJson(dHCSelfPayResultXml);

        //HIS业务
        if (CustomConstant.ZERO.equals(dHCSelfPayResult.getString("ResultCode"))) {
            return dHCSelfPayResult;
        } else {
            throw new BusinessException(BizErrorEnum.HIS_REMOTE_EXCEPTION,dHCSelfPayResult.getString("ResultContent"));
        }
    }


    //todo 实列  具体根据业务变化
    public JSONObject his3013(String name,String password) {


        StringBuffer hisParams = new StringBuffer();
        //参数组装
        hisParams.append("<Request>");
        hisParams.append("<TradeCode>").append("3013").append("</TradeCode>");
        hisParams.append("<name>").append(name).append("</name>");
        hisParams.append("<password>").append(password).append("</password>");
        hisParams.append("</Request>");
        //发起请求
        return this.invoke(hisParams.toString());

    }




}
